package com.taxi.driver.module.login;

import android.text.TextUtils;

import com.qianxx.network.RequestError;
import com.qianxx.utils.RxUtil;
import com.qianxx.utils.encode.RandomUtil;
import com.qianxx.utils.text.RegUtils;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.config.LoginStatus;
import com.taxi.driver.data.config.ConfigRepository;
import com.taxi.driver.data.entity.ConfigEntity;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.event.UIEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

/**
 * 功能描述：
 */
public class LoginPresenter extends BasePresenter implements LoginContract.Presenter {

    private LoginContract.View mView;
    private UserRepository mUserRepository;
    @Inject
    ConfigRepository mConfigRepository;
//    @Inject
//    AMapManager amapManager;
    @Inject
    public LoginPresenter(LoginContract.View view, UserRepository userRepository) {
        mView = view;
        mUserRepository = userRepository;
//        amapManager=mapManager;
    }

//    @Override
//    public void getCurrentCity() {
//        LatLng mCurrentLatLng = new LatLng(amapManager.getLastLocation().getLatitude(), amapManager.getLastLocation().getLongitude());
//
//        amapManager.geocodeSearch(mCurrentLatLng)
//                .compose(RxUtil.applySchedulers())
//                .subscribe(address -> {
//                    mView.getCurrentCity(address.getCity());
//
//                }, ex -> showNetworkError(ex, R.string.error, mView));
//    }

    @Override
    public void reqLogin(final String phone, String pwd, boolean isAgree) {
        if (TextUtils.isEmpty(phone)) {
            toast(R.string.login_empty_phone);
            return;
        }
        if (!RegUtils.isMobileNumber(phone)) {
            toast(R.string.login_error_phone);
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            toast(R.string.login_empty_pwd);
            return;
        }
        if (!isAgree) {
            toast(R.string.login_not_agree);
            return;
        }
        mUserRepository.reqLogin(RandomUtil.RandomEncrypt(phone), RandomUtil.RandomEncrypt(pwd))
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(true))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(driverEntity -> {
                    if (driverEntity.isFirst == LoginStatus.IS_FIRST) {
                        /* 首次登录，需要先修改密码 */
                        mView.loginIsFirst(phone);
                    } else {
                        saveAccount(phone);
                        /* 非首次登录，登录成功 */
                        mView.loginSuccess();
                    }
                }, ex -> {
                    if (ex instanceof RequestError) {
                        RequestError error = ((RequestError) ex);
                        if (error.getErrCode() == 10012) { //账号被封
                            mView.showAccountUnavailable(error.getMessage());
                            return;
                        }
                    }
                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
//                    /* 处理errCode */
//                    Throwable throwable = ex.getCause();
//                    if (throwable instanceof RequestError) {
//                        RequestError error = ((RequestError) throwable);
//                        mView.loginFail(error.getErrCode(), error.getMessage());
//                    }
                });
    }

    @Override
    public void saveAccount(String account) {
        mUserRepository.saveAccount(account);
    }

    @Override
    public String getAccount() {
        return mUserRepository.getAccount();
    }

    @Override
    public void saveDriverType(int type) {
        mUserRepository.saveDriverType(type);
    }

    @Override
    public int getDriverType() {
        return mUserRepository.getDriverType();
    }

    public void onCreate() {
        EventBus.getDefault().register(this);
    }

    public void onDestory() {
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUIEvent(UIEvent event) {
        switch (event.type) {
            case UIEvent.CLEAR_PWD:
                mView.clearPwd();
                break;
        }
    }

    @Override
    public void getConfig() {
        mConfigRepository.variable()
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(true))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(entitys -> {
                    for (ConfigEntity entity : entitys) {
                        if (entity.key.equals("about"))
                            mConfigRepository.saveAbout(entity.valule);
                        if (entity.key.equals("priceRules"))
                            mConfigRepository.savePriceRules(entity.valule);
                        if (entity.key.equals("ruleExplain"))
                            mConfigRepository.saveRuleExplain(entity.valule);
                        if (entity.key.equals("userAgreement"))
                            mConfigRepository.saveAgress(entity.valule);
                    }

                    mView.gotoAgree(mConfigRepository.getAgress());
                }, ex -> {
                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                });
    }

}
